from app.aoduo_admin.models import AdminOperationLog
from app.account.models import UserInfo
from django.http import JsonResponse
from rest_framework.views import APIView
from common.dictInfo import model_to_dict
from common.authCheck.adminAuth import check_admin_login, getAdminUser, adminAuthCheck
from common.paginator import paginator


class AdminUserListInfoView(APIView):
    INCLUDE_FIELDS = [
        'nickname', 'email', 'user_role', 'realName', 'id'
    ]

    @check_admin_login
    def get(self, request):
        """
        获取所有用户列表
        :param request:
        :return:
        """
        try:

            admin_user = getAdminUser(request.session.get('admin'))
            # 检查管理员权限
            authID = 3
            if adminAuthCheck(admin_user, authID):
                # 记录操作行为
                AdminOperationLog.objects.create(
                    related_admin_id=admin_user.id,
                    related_auth_type_id=authID,
                    other_message='view user list'
                )
                allUser = UserInfo.objects.all()
                pageAllUser = paginator(allUser, request.GET.get('page'), 50)
                allUserDict = [model_to_dict(user, fields=self.INCLUDE_FIELDS) for user in pageAllUser]
                return JsonResponse({
                    'status': True,
                    'all_user': allUserDict,
                    'has_previous': pageAllUser.has_previous(),
                    'has_next': pageAllUser.has_next()
                })
            return JsonResponse({
                'status': False,
                'errMsg': '你没有权限操作'
            }, status=401)
        except Exception as e:
            return JsonResponse({
                'status': False,
                'errMsg': str(e)
            })
